package com.catena.web.config;

import com.catena.core.CatenaContext;
import com.catena.core.CatenaControllerBase;
import com.catena.mock.MockRuntimeException;
import com.catena.mock.core.ScanProjectContext;
import com.catena.mock.inject.InjectionLoading;
import com.catena.web.interceptor.MockUrlConditionalInterceptor;
import com.lyncode.jtwig.mvc.JtwigViewResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;
import java.util.List;

/**
 * Created by hx-pc on 16-5-17.
 */
@Configuration
public class MockConfig extends WebMvcConfigurationSupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(MockConfig.class);

    @Value ("${spring.twig.cache:true}")
    private Boolean twigCache;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(mockUrlConditionalInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/init","/api/*/init")
                .excludePathPatterns("/api/project")
                .excludePathPatterns("/api/socket")
                .excludePathPatterns("/api/mock", "/favicon.ico", "/error");

    }

    @Bean
    protected MockUrlConditionalInterceptor mockUrlConditionalInterceptor() {
        return new MockUrlConditionalInterceptor();
    }

    @Bean
    protected CatenaContext catenaContext() {
        return CatenaControllerBase.catenaContext;
    }

    @Bean
    public ScanProjectContext scanUrlAndDataContext() {
        try {
            return new ScanProjectContext();
        } catch (IOException e) {
            LOGGER.error("{}", "初始化ScanProjectContext失败." + e);
            throw new MockRuntimeException(499, "初始化ScanProjectContext失败");
        }
    }

    @Bean
    public InjectionLoading getInjectionLoading() {
        return new InjectionLoading();
    }


    @Bean
    public ViewResolver viewResolver() {
        JtwigViewResolver viewResolver = new JtwigViewResolver();
        viewResolver.setPrefix("classpath:html/");
        viewResolver.setSuffix(".html");
        viewResolver.setEncoding("UTF8");
        viewResolver.setCache(false);
        viewResolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
        viewResolver.configuration().render();

        /*//和上面等价,只是不能使用jtwig语法,也可以在properties里面配置
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/html/");
        viewResolver.setSuffix(".html");
        viewResolver.setCache(false);
        viewResolver.setViewClass(InternalResourceView.class);
        viewResolver.setOrder(Ordered.HIGHEST_PRECEDENCE);*/
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(MethodParameter methodParameter) {
                System.out.println(methodParameter);
                return false;
            }

            @Override
            public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
                return null;
            }
        });
        super.addArgumentResolvers(argumentResolvers);
    }
}
